# 作者：陈睿-cruise
# 2025年02月19日19时06分16秒
# 2979386061@qq.com
import re

# 示例字符串
text = "Alice is 30, Bob is 25, Charlie is 35. I like apples or bananas."

# 1. 使用 | 匹配左右任意表达式（例如：匹配 'apples' 或 'bananas'）
pattern1 = r"apples|bananas"
matches1 = re.findall(pattern1, text)
print("匹配 'apples' 或 'bananas':", matches1)

# 2. 使用 () 创建分组，匹配名字和年龄
pattern2 = r"(\w+) is (\d+)"
matches2 = re.findall(pattern2, "Alice is 30, Bob is 25, Charlie is 35.")
print("匹配名字和年龄：", matches2)

# 3. 使用分组编号进行替换：替换为 '年龄 years old, 名字'
replacement = r"\2 years old, \1"
new_text = re.sub(pattern2, replacement, "Alice is 30, Bob is 25, Charlie is 35.")
print("替换后的文本（使用编号）：", new_text)

# 4. 使用命名分组匹配：捕获名字和年龄
pattern3 = r"(?P<name>\w+) is (?P<age>\d+)"
matches3 = re.findall(pattern3, "Alice is 30, Bob is 25, Charlie is 35.")
print("匹配命名分组结果：", matches3)

# 5. 使用命名分组进行替换：使用别名进行替换
replacement2 = r"\g<age> years old, \g<name>"
new_text2 = re.sub(pattern3, replacement2, "Alice is 30, Bob is 25, Charlie is 35.")
print("替换后的文本（使用别名）：", new_text2)
